﻿using Microsoft.EntityFrameworkCore;
using PHMEE.Entities.DaqInfo.TdDevices;
using PHMEE.EntityFrameworkCore;
using PHMEE.IRepositories.DaqInfo.TdDevices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PHMEE.Repositories.DaqInfo.TdDevices
{
    /// <summary>
    /// 定义 TdDevicePointRelation 的自定义仓储实现
    /// </summary>
    public class TdDevicePointRelationRepository : ITdDevicePointRelationRepository
    {
        private readonly PHMEEDbContext _dbContext;

        public TdDevicePointRelationRepository(PHMEEDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        public async Task<List<TdDevicePointRelation>> GetRelationsByInstanceIdAsync(Guid tdDeviceInstanceId)
        {
            return await _dbContext.Set<TdDevicePointRelation>()
                .Where(r => r.TdDeviceInstanceId == tdDeviceInstanceId)
                .ToListAsync();
        }

        public async Task<TdDevicePointRelation> GetRelationByPointIdAsync(Guid pointId)
        {
            return await _dbContext.Set<TdDevicePointRelation>()
                .Include(item => item.TdDeviceInstance)
                .ThenInclude(item => item.TdDeviceType)
                .ThenInclude(item => item.Database)
                .FirstOrDefaultAsync(r => r.PointId == pointId);
        }

        public async Task<List<TdDevicePointRelation>> GetRelationsAsync(List<Guid> pointIds)
        {
            return await _dbContext.Set<TdDevicePointRelation>()
                .Where(item => pointIds.Contains(item.PointId))
                .Include(item => item.TdDeviceInstance)
                .ThenInclude(item => item.TdDeviceType)
                .ThenInclude(item => item.Database)
                .ToListAsync();
        }

        public async Task AddAsync(TdDevicePointRelation relation)
        {
            _dbContext.Set<TdDevicePointRelation>().Add(relation);
            await _dbContext.SaveChangesAsync();
        }

        public async Task AddRangeAsync(List<TdDevicePointRelation> relations)
        {
            await _dbContext.Set<TdDevicePointRelation>().AddRangeAsync(relations);
            await _dbContext.SaveChangesAsync();
        }

        public async Task UpdateAsync(TdDevicePointRelation relation)
        {
            _dbContext.Set<TdDevicePointRelation>().Update(relation);
            await _dbContext.SaveChangesAsync();
        }

        public async Task UpdateRangeAsync(List<TdDevicePointRelation> relations)
        {
            _dbContext.Set<TdDevicePointRelation>().UpdateRange(relations);
            await _dbContext.SaveChangesAsync();
        }

        public async Task DeleteRangeAsync(List<TdDevicePointRelation> relations)
        {
            _dbContext.Set<TdDevicePointRelation>().RemoveRange(relations);
            await _dbContext.SaveChangesAsync();
        }

    }

}
